package com.szxy.common.zuul.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Auther:zwer
 * @Date:2019/9/26 16:56
 * @Description:com.szxy.common.zuul.fallback
 * @Version:1.0
 **/
@Component
public class FrontendOrderFallBack implements FallbackProvider {

    /**
     * 针对哪个网关代理服务进行降级
     * 注意：被网关代理的服务自身不需要再做服务容灾 hystrix
     * 而像中游、下游服务需要自己做服务容灾处理
     * @return
     */
    @Override
    public String getRoute() {
        return  "frontend-order";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        if(cause != null && cause.getCause() != null){
            String msg = cause.getCause().getMessage();
            System.out.println(route+"\t"+msg);
        }
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String body = "frontend portal fallback";
                return new ByteArrayInputStream(body.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                MediaType mediaType
                        = new MediaType("application","json", Charset.forName("utf-8"));
                httpHeaders.setContentType(mediaType);
                return httpHeaders;
            }
        };
    }
}
